package permission

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminlog"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminLogListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminLogListLogic - 后台日志查询接口
func NewAdminLogListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminLogListLogic {
	return &AdminLogListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminLogListLogic) AdminLogList(req *types.AdminLogListRequest) (resp *types.AdminLogListResponse, err error) {
	adminLogDao := permission.NewAdminLogDao(l.ctx, l.svcCtx)

	// 条件查询日志
	adminLogCond := make([]predicate.AdminLog, 0)
	if req.AdminLogIp != "" {
		adminLogCond = append(adminLogCond, adminlog.AdminLogIPEQ(req.AdminLogIp))
	}
	if req.AdminLogOperateSystem != "" {
		adminLogCond = append(adminLogCond, adminlog.AdminLogOperateSystemContains(req.AdminLogOperateSystem))
	}
	if req.AdminLogUrl != "" {
		adminLogCond = append(adminLogCond, adminlog.AdminLogURLContains(req.AdminLogUrl))
	}
	if req.AdminLogPage != "" {
		adminLogCond = append(adminLogCond, adminlog.AdminLogPageContains(req.AdminLogPage))
	}
	if req.AdminLogAccount != "" {
		adminLogCond = append(adminLogCond, adminlog.AdminLogAccountEQ(req.AdminLogAccount))
	}
	adminLogList, total, err := adminLogDao.AdminLogConditionsPageAll(req, adminLogCond)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询用户列表失败: %v", err.Error()))
	}

	// 组装数据
	list := lo.Map(adminLogList, func(item *ent.AdminLog, _ int) *types.AdminLogInfo {
		return &types.AdminLogInfo{
			ID:                    int64(item.ID),
			AdminLogAccount:       item.AdminLogAccount,
			AdminLogIp:            item.AdminLogIP,
			AdminLogUrl:           item.AdminLogURL,
			AdminLogPage:          item.AdminLogPage,
			AdminLogOperateSystem: item.AdminLogOperateSystem,
			AdminLogBrowser:       item.AdminLogBrowser,
			AdminLogExtraInfo:     item.AdminLogExtraInfo,
			CreateAt:              item.CreateAt.Format(time.DateTime),
		}
	})

	// 返回数据
	return &types.AdminLogListResponse{
		Page: &types.PageResponse{
			Total:           int64(total),
			PageSize:        int64(len(list)),
			RequestPageSize: req.PageSize,
			Current:         req.Current,
		},
		List: list,
	}, nil
}
